#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os,time
import re,datetime,rrdtool

def graphcreat(customer,qs):
  rrd_list=[]
  graph_file_name_list=[]
  graph_title_graph_name_dict={}
  if qs:
    user_days=int(qs) 
  else:
    user_days=1
  now=datetime.datetime.now().strftime('%Y-%m-%d %H\:%M\:%S')
  ago=(datetime.datetime.now()-datetime.timedelta(days=user_days)).strftime('%Y-%m-%d %H\:%M\:%S')
  graph_timerange="From "+ago+" TO "+now
  graph_name_time=str(int(time.time()))

  for home, dirs, files in os.walk("/var/rra/%s" %customer):
    for rrd_filename in files:
      rrd_list.append(rrd_filename)

  for rrd in rrd_list:
        rrd_re_str=re.split('[.]',rrd)
        graph_file_name=rrd_re_str[0]+graph_name_time
        #graph_file_name_re=re.split('[ ]',graph_file_name_space)
        #graph_file_name=graph_file_name_re[0]+graph_file_name_re[1]
        A_Z_re_str=re.split('[,]',rrd_re_str[0])
        graph_title=A_Z_re_str[0]+" TO "+A_Z_re_str[1]
        graph_title_graph_name_dict[graph_title]=graph_file_name
        rrdtool.graph("/var/www/static/traffic_graph/%s.png" %graph_file_name,
              "--start","N-%dd" %user_days,
              "-w","600","-h","120", 
              "--title=%s" %graph_title,
              "DEF:value1=/var/rra/%s/%s:out:AVERAGE" %(customer,rrd),
              "DEF:value3=/var/rra/%s/%s:in:AVERAGE" %(customer,rrd),
              "CDEF:value2=value1,8,*",
              "CDEF:value4=value3,8,*", 
              "COMMENT:%s\c" %graph_timerange, 
              "COMMENT: \\r",
              "--vertical-label=bits per second",
              "AREA:value4#00CF00:In",
              "GPRINT:value4:LAST: Current\:%8.2lf %s",
              "GPRINT:value4:AVERAGE:Average\:%8.2lf %s",
              "GPRINT:value4:MAX:Maximum\:%8.2lf %s", 
              "COMMENT:\\r",
              "LINE1:value2#002A97:Out",
              "GPRINT:value2:LAST:Current\:%8.2lf %s",
              "GPRINT:value2:AVERAGE:Average\:%8.2lf %s",
              "GPRINT:value2:MAX:Maximum\:%8.2lf %s", 
              "COMMENT:\\r")
  return(graph_title_graph_name_dict)